package com.future.common.interceptor;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.executable.ExecutableValidator;

import com.future.common.exception.BadRequestException;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
/**
 * controller参数拦截器
 * @author ThinkPad
 *
 */
public class RequestParasValidator implements Interceptor {
	private final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

	@Override
	public void intercept(Invocation inv) {
		ExecutableValidator validatorParam = validator.forExecutables();
		/*
		 *在方法执行之前会对参数值进行校验 
		 */
		Set<ConstraintViolation<Object>> constraintViolationSet = validatorParam.validateParameters(inv.getController(), inv.getMethod(), inv.getArgs());
		if(constraintViolationSet.size()>0){
			ConstraintViolation<Object> constraintViolations  = constraintViolationSet.stream().findFirst().get();
			throw new BadRequestException(constraintViolations.getMessage());
		}
		inv.invoke();
	}

}
